package com.magicborrow.activity;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.magicborrow.Constants;
import com.magicborrow.R;
import com.magicborrow.beans.HomePageEntity;
import com.magicborrow.beans.StuffBean;
import com.magicborrow.beans.UserBean;
import com.magicborrow.huanxin.ChatActivity;
import com.magicborrow.utils.UIHelper;
import com.magicborrow.utils.UserTools;
import com.magicborrow.utils.VolleyTool;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2016/5/18.
 */
public class HomepageActivity extends BaseActivity implements View.OnClickListener, VolleyTool.HTTPListener {

    private ImageView ivEdit;
    private ImageView ivGender;
    private ImageView ivBack;
    private ImageView avater;
    private TextView tvName;
    //    private TextView tvAddress;
    private TextView tvIntro;
    private int accoutId;
    private RecyclerView mRecyclerView;
    private RatingBar rbBorrow;
    private TextView score0;
    private TextView comment0;
    private RatingBar rbLend;
    private TextView score1;
    private TextView comment1;
    private ThingImageAdapter thingImageAdapter;
    private String signature;
    private ImageView goMessage;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_homepage);
        setHasTitle(false);
        initView();
        setTop();
        initData();
        initListener();
    }

    @TargetApi(Build.VERSION_CODES.KITKAT)
    private void setTop() {
        Window window = getWindow();

        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        TextView tvTop = (TextView) findViewById(R.id.v_top);
        tvTop.setHeight(UIHelper.getStatusHeight(this));

        tvTop.setVisibility(View.VISIBLE);
    }

    private void initView() {
        avater = (ImageView) findViewById(R.id.avatar);
        ivGender = (ImageView) findViewById(R.id.iv_boy);
        tvName = (TextView) findViewById(R.id.name);
//        tvAddress = (TextView) findViewById(R.id.address);
        tvIntro = (TextView) findViewById(R.id.intro);
        ivEdit = (ImageView) findViewById(R.id.iv_edit);
        ivBack = (ImageView) findViewById(R.id.iv_back);

        goMessage = (ImageView) findViewById(R.id.goMessage);
        rbBorrow = (RatingBar) findViewById(R.id.rb_borrow);
        score0 = (TextView) findViewById(R.id.score0);
        comment0 = (TextView) findViewById(R.id.comment0);

        rbLend = (RatingBar) findViewById(R.id.rb_lend);
        score1 = (TextView) findViewById(R.id.score1);
        comment1 = (TextView) findViewById(R.id.comment1);
        TextView textView = (TextView) findViewById(R.id.tv_t);
        if(UserTools.getUser(this) != null) {
            if (UserTools.getUser(this).getId() != accoutId) {
                textView.setText("他发布的物品");
            }
        }
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
//        FullyGridLayoutManager manager = new FullyGridLayoutManager(this, 2);
        LinearLayoutManager manager = new LinearLayoutManager(this);

        manager.setOrientation(LinearLayoutManager.HORIZONTAL);
        mRecyclerView.setLayoutManager(manager);
    }

    private void initData() {
        accoutId = getIntent().getIntExtra("id", 0);


        // ivEdit.setVisibility(getIntent().hasExtra("mine")?View.VISIBLE:View.GONE);
        thingImageAdapter = new ThingImageAdapter();
        mRecyclerView.setAdapter(thingImageAdapter);

    }

    private void sendRequest() {
        Map<String, String> params = new HashMap<>();
        params.put("id", accoutId + "");
        VolleyTool.get(Constants.HOME_PAGE, params, this, Constants.REQUEST_ONE, HomePageEntity.class);
    }


    @Override
    protected void onResume() {
        super.onResume();
        sendRequest();
    }

    private UserBean.User user = null;

    @Override
    public <T> void onResponse(T t, int requestCode) {
        if (requestCode == Constants.REQUEST_ONE) {
            HomePageEntity entity = (HomePageEntity) t;
            if (entity.getCode() >= 0) {
                HomePageEntity.HomePageData data = entity.getData();
                user = entity.getData().getUser();

                DisplayImageOptions options = new DisplayImageOptions.Builder().displayer
                        (new RoundedBitmapDisplayer(getResources().getDimensionPixelOffset(R.dimen._50dp))).build();
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().displayImage(
                        Constants.ADDRESS + data.getUser().getAvatar80(),
                        avater, options);
                tvName.setText(data.getUser().getNickname());
                ivGender.setBackgroundResource(data.getUser().getGender() == 1 ? R.mipmap.boy : R.mipmap.girl);
                signature = user.getSignature();
                tvIntro.setText(signature);

                rbBorrow.setRating(Float.parseFloat(user.getBorrowScaleAVG() + ""));
                score0.setText(user.getBorrowScaleAVG() + "分");
                comment0.setText(user.getBorrowTimes() + "人评价");

                rbLend.setRating(Float.parseFloat(user.getLendScaleAVG() + ""));
                score1.setText(user.getLendScaleAVG() + "分");
                comment1.setText(user.getLendTimes() + "人评价");

                //借出和借入评价
                thingImageAdapter.setImages(data.getWares());
                thingImageAdapter.notifyDataSetChanged();
                boolean bol = getIntent().hasExtra("mine");
                if (bol) {
                    ivEdit.setVisibility(View.VISIBLE);
                    goMessage.setVisibility(View.GONE);
                } else {
                    ivEdit.setVisibility(View.GONE);
                    goMessage.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void onErrorResponse(VolleyError error, int requestCode) {

    }

    private void initListener() {
        ivBack.setOnClickListener(this);
        ivEdit.setOnClickListener(this);
        goMessage.setOnClickListener(this);
        avater.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_edit://修改
                Intent intent = new Intent();
                intent.setClass(this, EditInfoActivity.class);
                intent.putExtra("signature", signature);
                startActivity(intent);
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.avatar:
                intent = new Intent(this, CommonViewPagerActivity.class);
                intent.putExtra("position", 0);
                ArrayList<String> imgUrls = new ArrayList<>();
                imgUrls.add(user.getAvatar());
                intent.putExtra("netImageUrls", imgUrls);

                startActivity(intent);

                break;
            case R.id.goMessage:
                if (UserTools.getUser(this) == null) {
                    return;
                }
                startActivity(new Intent(this, ChatActivity.class).putExtra("chatType", 1)
                        .putExtra("userId", user.getId() + "")
                        .putExtra("username", user.getNickname()).putExtra("avatarPath",
                                user.getAvatar80()));
                break;
        }
    }


    class ThingImageAdapter extends RecyclerView.Adapter {
        private List<StuffBean> wares = new ArrayList<>();
        private List<StuffBean.ImagesEntity> images;

        public void setImages(List<StuffBean> wares) {
            this.wares = wares;
        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            View view = View.inflate(parent.getContext(), R.layout.item_imagething, null);
            return new ThingViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
            if (holder instanceof ThingViewHolder) {
                images = wares.get(position).getImages();
                if (images.size() > 0) {
                    VolleyTool.getImageLoader().get(Constants.ADDRESS + images.get(0).getPreview(), new ImageLoader.ImageListener() {
                        @Override
                        public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                            Bitmap bitmap = response.getBitmap();
                            if (bitmap != null) {
                                ((ThingViewHolder) holder).ivImagething.setImageBitmap(bitmap);
                            }
                        }

                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    });
                } else {
                    ((ThingViewHolder) holder).ivImagething.setBackgroundResource(R.mipmap.img_default);
                }
                ((ThingViewHolder) holder).tvThing.setText(wares.get(position).getName());
                int price = wares.get(position).getPrice();
                int priceMode = wares.get(position).getPriceMode();
                switch (priceMode) {
                    case 0:
                        ((ThingViewHolder) holder).tvThingPrice.setText("￥ " + price + "/" + PriceMode.Secondary.getMode());
                        break;
                    case 1:
                        ((ThingViewHolder) holder).tvThingPrice.setText("￥ " + price + "/" + PriceMode.Hour.getMode());
                        break;
                    case 2:
                        ((ThingViewHolder) holder).tvThingPrice.setText("￥ " + price + "/" + PriceMode.Day.getMode());
                        break;
                    case 3:
                        ((ThingViewHolder) holder).tvThingPrice.setText("￥ " + price + "/" + PriceMode.Week.getMode());
                        break;
                }
                //((ThingViewHolder) holder).ivImagething.setOnClickListener(new MyOnClickListener(position,wares));
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(HomepageActivity.this, BorrowStuffDetailActivity.class);
                        intent.putExtra("data", wares.get(position));
                        HomepageActivity.this.startActivity(intent);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return wares.size();
        }
    }


    class MyOnClickListener implements View.OnClickListener {
        private int position;
        private List<StuffBean> mWares;

        public MyOnClickListener(int position, List<StuffBean> wares) {
            this.position = position;
            this.mWares = wares;
        }

        @Override
        public void onClick(View view) {
//            if (mWares.get(position).getImages().size()!=0){
//                Intent intent = new Intent(HomepageActivity.this, DetailPicActivity.class);
//                Bundle mBundle = new Bundle();
//                List<StuffBean.ImagesEntity> images = mWares.get(position).getImages();
//                mBundle.putSerializable("images",(Serializable) images);
//                intent.putExtras(mBundle);
//                startActivity(intent);
//            }

        }
    }


    enum PriceMode {
        Secondary("次"), Hour("小时"), Day("天"), Week("周");

        String mode;

        PriceMode(String mode) {
            this.mode = mode;
        }

        public String getMode() {
            return mode;
        }
    }

    class ThingViewHolder extends RecyclerView.ViewHolder {

        public ImageView ivImagething;
        public TextView tvThing;
        public TextView tvThingPrice;

        public ThingViewHolder(View itemView) {
            super(itemView);
            ivImagething = (ImageView) itemView.findViewById(R.id.iv_imagething);
            tvThing = (TextView) itemView.findViewById(R.id.tv_thing);
            tvThingPrice = (TextView) itemView.findViewById(R.id.tv_thing_price);
        }
    }
}
